<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/7/6
 * Time: 16:49
 * @author: yfl
 * @QQ: 554665488
 * @description:
 * @time:
 */

namespace app\oa\controller;

use app\oa\logic\User as UserLogicModel;
use app\oa\model\User;
use think\Config;
use think\Request;
use think\Session;

/**
 * @author: yfl
 * @QQ: 554665488
 * @description:  OA 登录控制器
 * @time: 2017年7月6日 16:50:59
 * Class LoginController
 * @package app\oa\controller
 */
class LoginController extends CommonController
{


    /**
     * @author: yfl
     * @QQ: 554665488
     * @description: 登录入口
     * @time: 2017-7-6 16:55:29
     */
    public function login()
    {
        if (Request::instance()->isGet()) {
            return $this->fetch('login');
        } elseif (Request::instance()->isPost()) {
            $data = Request::instance()->post();
            $res = UserLogicModel::login($data);
            if (is_object($res)) {
                if (!Session::has('user_info', 'oa')) {
                    Session::set('user_info', $data, 'oa');
                }
                return self::showReturnCodeWithOutData('loginSuccess', '登录成功...');
//                $this->redirect('/report');
            } else {
                self::toSaveLog(404, '保存日志');
                return self::showReturnCodeWithOutData(-1, $res);
            }
        } else {
            return self::showReturnCodeWithOutData(404);
        }

    }

    /**
     * @author: yfl
     * @QQ: 554665488
     * @description: 需要整理
     * @time:
     */
    public function wxLogin()
    {
        $config = Config::get('thirdlogin.weixin');
        // 获取回调地址 http://xxx.com/        public/home/Wxlogin/index
        $url = request()->root(true) . '/' . request()->path();
//         trace('weixin url '.$url);
        $url = urlencode($url);
        // 公众号的id和secret
        $appid = $config['appid'];
        $appsecret = $config['appsecret'];

        // 获取code码，用于和微信服务器申请token。 注：依据OAuth2.0要求，此处授权登录需要用户端操作
        if (!isset($_GET['code']) && !isset($_SESSION['code'])) {
            //以下信息可安放在用户登录界面上：
            $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $appid . '&redirect_uri=' . $url . '&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect';
            header('Location:' . $url);//跳转到第三方登录入口
            exit;
        }

        // 依据code码去获取openid和access_token，自己的后台服务器直接向微信服务器申请即可
        if (isset($_GET['code']) && !isset($_SESSION['token'])) {
            $_SESSION['code'] = $_GET['code'];

            $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $appid .
                "&secret=" . $appsecret . "&code=" . $_GET['code'] . "&grant_type=authorization_code";
            $res = $this->https_request($url);
            $res = (json_decode($res, true));
            $_SESSION['token'] = $res;
        }

        //  print_r($_SESSION);

        // 依据申请到的access_token和openid，申请Userinfo信息。
        if (isset($_SESSION['token']['access_token'])) {
            $url = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $_SESSION['token']['access_token'] . "&openid=" . $_SESSION['token']['openid'] . "&lang=zh_CN";
            //echo $url;
            $res = $this->https_request($url);
            $res = json_decode($res, true);//最终得到的用户信息


            $_SESSION['userinfo'] = $res;

            header('Location:' . Url('User/thirdlogin?userfrom=1'));//跳转到第三方登录入口
            exit;
        }
    }

    /**
     * @author: yfl
     * @QQ: 554665488
     * @description: 注册用户
     * @time: 2017年7月10日 08:27:32
     * @param Request $request
     * @return array|mixed
     */
    public function register(Request $request)
    {
        if ($request->isGet()) {
            $data = User::getPartPerson();

            $this->assign('list', array_recursion($data));
            return $this->fetch('register');
        }
        if ($request->isPost()) {
            $data = $request->post();
            if (!empty($data)) {
                $saveData['mobile'] = $data['mobile'];
                $saveData['realname'] = $data['realname'];
                $saveData['password'] = encode($data['password']);
                $saveData['department_id'] = $data['department_id'];
                $saveData['duty_id'] = $data['duty_id'];
                $saveData['upuid'] = $data['upuid'];
                $res = User::addUser($saveData);
                if (is_array($res)) {
                    return self::showReturnCodeWithOutData(-1, '数据验证不通过', $res);
                }
                if (is_string($res)) {
                    return self::showReturnCodeWithOutData(-1, $res);
                }
                if (is_numeric($res)) {
                    return self::showReturnCodeWithOutData(1, '注册成功');
                }
            } else {
                return self::showReturnCodeWithOutData(-1, '数据错误');
            }

        }
    }

    /**
     * @author: yfl
     * @QQ: 554665488
     * @description: 退出
     * @time:2017年7月14日 10:23:18
     */
    public function logout()
    {
        if (Session::has('user_info', 'oa')) {
        }
        Session::delete('user_info', 'oa');
        $this->redirect('/login');
    }

    /**
     * @author: yfl
     * @QQ: 554665488
     * @description: 修改个人资料
     * @time: 2017年7月14日 13:25:10
     * @param Request $request
     * @return array|mixed
     */
    public function modify(Request $request)
    {
        $mobile = getSession('mobile');
        if (empty($mobile)) {
            $this->redirect('/login');
        }
        $userData = User::getUserInfoByMobile($mobile);
        if ($request->isGet()) {
            $this->assign('data', $userData);
            return $this->fetch('modify');
        }
        if ($request->isPost()) {
            $data = $request->post();
            if (!empty($data)) {
                if (UserLogicModel::isRegister($data['mobile']) === false) {
                    return self::showReturnCodeWithOutData(-1, '用户不存在');
                }
                $getUserObj = User::getUserInfoByMobile($data['mobile'], true);
                if ($getUserObj->password === encode($data['password_old'])) {
                    $res = model('User', 'logic')->modifyPassword($getUserObj, $data['password_new']);
                    if ($res) {
                        return self::showReturnCodeWithOutData(1, '修改成功,重新登录..');
                    } else {
                        return self::showReturnCodeWithOutData(-1, '修改失败');
                    }
                } else {
                    return self::showReturnCodeWithOutData(-1, '旧密码不正确');
                }
            } else {
                return self::showReturnCodeWithOutData(-1, '提交的数据错误');
            }
        }
    }

}